﻿/*-----------------------------------------------------------------------
 * <copyright file="FormProjectQueryCtrl.xaml.cs" company="O-RID">
 *     Copyright (c)2010 O-RID Co.,Ltd.
 * </copyright>
 * <author>Zhang jun </author>
 * <summary>
 *          帳票工程別情報查询
 * 
 *  开始日期: 2010-9-9
 *  作成日:   2010-9-13
 *            09/28/0210 增加 分页记录数可自定义
 *            10/14/2010 修改 导出功能异常
 * </summary>
 *----------------------------------------------------------------------- 
*/
namespace Orid.Management.Statistics.OperatorUnitMangement.MatterRelated.FormProjectQuery
{
    using System;
    using System.Collections.Generic;
    using System.Threading;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Windows.Media;
    using Orid.Management.Statistics.OperatorUnitMangement.Common.Export;
    using Orid.Management.Statistics.OperatorUnitMangement.Common.FunctionList;
    using Orid.Management.Statistics.OperatorUnitMangement.Common.SearchCtrl;
    using Orid.Management.Statistics.OperatorUnitMangement.WCFServers.MatterQueryRef;
    using childWindow = Orid.Management.Statistics.OperatorUnitMangement.Common.Window;
    using Wcf = Orid.Management.Statistics.OperatorUnitMangement.Common.Service;

    /// <summary>
    /// 帳票工程別情報查询
    /// </summary>
    public partial class FormProjectQueryCtrl : UserControl
    {
        #region 全局变量
        /// <summary>
        /// 当前查询框的名字（日志用）
        /// </summary>
        private string ctrlName = " 帳票工程別情報 ";

        /// <summary>
        /// 查询区域对象
        /// MatterSelContainer
        /// </summary>
        private Common.SearchCtrl.MatterSelContainer matterSelcontainer;

        /// <summary>
        /// 查询子窗体 lineSelectWin
        /// </summary>
        childWindow.LineSelChildWin lineSelect = null;

        /// <summary>
        /// 消息子窗体 errorMessbox
        /// </summary>
        private childWindow.MessageBox errorMessbox = null;

        /// <summary>
        /// 日志服务定义
        /// wcfLogClient
        /// </summary>
        private WCFLog4Ref.WCFLog4Client wcfLogClient = null;

        /// <summary>
        /// 分页控件
        /// PagedCollectionView
        /// </summary>
        private PagedCollectionView pcv;

        /// <summary>
        /// 记录要导出的数据
        /// </summary>
        List<string[]> dataListToCSV = null;

        /// <summary>
        /// DataGrid数据源
        /// </summary>
        List<string[]> getListSource = null;

        #endregion 全局变量


        /// <summary>
        /// 帳票工程別情報查询
        /// </summary>
        public FormProjectQueryCtrl(MatterSelContainer matterSelcontainer)
        {
            InitializeComponent();

            // 引用主题
            ((App)Application.Current).SetTheme((Grid)LayoutRoot);

            this.dgFormProject.HeadersVisibility = DataGridHeadersVisibility.All;//同时显示DataGrid的行头与列头

            this.matterSelcontainer = matterSelcontainer;

            this.InitField();

            #region 查询设置
            Command.Matter.FormProjectQuery queryCommand = new Command.Matter.FormProjectQuery(matterSelcontainer);

            queryCommand.ExecOver -= new EventHandler<SelectFormProjectQueryInforCompletedEventArgs>(queryCommand_ExecOver);
            queryCommand.ExecBegin -= new EventHandler<EventArgs>(this.QueryCommand_ExecBegin);

            queryCommand.ExecOver += new EventHandler<SelectFormProjectQueryInforCompletedEventArgs>(queryCommand_ExecOver);
            queryCommand.ExecBegin += new EventHandler<EventArgs>(this.QueryCommand_ExecBegin);

            this.matterSelcontainer.QueryCcommand = queryCommand;
            #endregion 查询设置

            #region 导出设置
            //导出
            Command.DateExport exportCommand = new Command.DateExport();
            //导出开始
            exportCommand.ExecBegin += new EventHandler<EventArgs>(this.ExportCommand_ExecBegin);

            this.matterSelcontainer.ExportComand = exportCommand;

            #endregion 导出设置

            //查询按钮可用
            this.matterSelcontainer.btnSelList.IsEnabled = true;
            //导出按钮可用
            this.matterSelcontainer.btnExport.IsEnabled = true;
            this.nuPageSize.IsEnabled = true; //分页数量 09/28/2010 Add

            // 设置背景色
            LayoutRoot.Background = new SolidColorBrush(Color.FromArgb(255, 243, 244, 245));

        }

        /// <summary>
        /// 变量初始化方法  InitField
        /// </summary>
        private void InitField()
        {
            this.lineSelect = new childWindow.LineSelChildWin();
            this.errorMessbox = new childWindow.MessageBox();
            this.wcfLogClient = Wcf.Service.Log4;
            this.dataListToCSV = new List<string[]>();
          
            //DataGrid数据源
            this.getListSource = new List<string[]>();
        }

        /// <summary>
        /// 查询开始
        /// QueryCommand_ExecBegin
        /// </summary>
        /// <param name="sender">sender of object</param>
        /// <param name="e">e type of RoutedEventArgs</param>
        private void QueryCommand_ExecBegin(object sender, EventArgs e)
        {
            this.SetBusyBar(100);
        }

        #region 查询符合条件的OP信息

        /// <summary>
        /// 查询符合条件的OP信息(查询按钮)
        /// </summary>
        /// <param name="sender">sender of object</param>
        /// <param name="e">e type of SelectFormProjectQueryInforCompletedEventArgs</param>
        private void queryCommand_ExecOver(object sender, SelectFormProjectQueryInforCompletedEventArgs e)
        {
            try
            {
                if (e.Error == null)
                {
                    if (e.Result.Count > 0)
                    {
                        #region ----把传来的e.Result变成List<String[]>的形式----

                        //DataGrid数据源
                        this.getListSource.Clear();

                        //一共有多少个outDateTime
                        int outDateTimeNum = e.Result[0].OutDateTime.Count;
                        //一共有多少个属性
                        int attributeNum = e.Result[0].GetType().GetProperties().Length;

                        //列数
                        int m = 0;
                        foreach (FormInforBasedData setClass in e.Result)
                        {
                            //WCF数据源中FormInforBasedData类
                            //所以，attributeNum - 1
                            String[] strAdd = new String[outDateTimeNum + attributeNum - 1];

                            strAdd[m++] = setClass.MatterName; //帳票名称 [0]
                            strAdd[m++] = setClass.KindName; //項目 [1]

                            //日期 //从[2]开始
                            for (int j = 0; j < setClass.OutDateTime.Count; j++)
                            {
                                strAdd[m++] = setClass.OutDateTime[j].ToString();
                            }

                            strAdd[m++] = setClass.Average; //平均 [日期的最后一个下标加1]
                            getListSource.Add(strAdd);
                            m = 0;

                        }

                        #endregion ----把传来的e.Result变成List<String[]>的形式----

                        // 把转换的LIST给 pcv 作为分页源
                        this.pcv = new PagedCollectionView(getListSource);
                        this.pcv.PageSize = Convert.ToInt32(this.nuPageSize.Value);

                        this.dgFormProject.ItemsSource = null;
                        this.dpDataPage.DataContext = null;

                        #region 动态生成 DataGarid

                        //清除之前动态生成的列
                        FunctionClass.clearColumn(this.dgFormProject, 2);

                        this.dgFormProject.ItemsSource = this.pcv;
                        this.dpDataPage.DataContext = this.pcv;

                        //记录LIST<STRING[]>中，日期字段的对应下标号。
                        int colNum = 0;

                        // 动态生成日期列字段
                        for (int i = 0; i < outDateTimeNum; i++)
                        {
                            //在此LIST 中 日期字段的对应下标号从[2]开始。
                            colNum = 2 + i;

                            //转换为日式日期
                            string str = FunctionClass.setDataTimeFormat(this.matterSelcontainer.startDataTime);

                            DataGridTextColumn templateColumn = new DataGridTextColumn();
                            templateColumn.Header = str;
                            templateColumn.Binding = new Binding("[" + colNum + "]");

                            //绑定单元格样式
                            templateColumn.CellStyle = App.Current.Resources["DataGrid_Cell_Right"] as Style;

                            this.dgFormProject.Columns.Add(templateColumn);

                            //天数加1（主要是为了取下一天的日期做表头）
                            this.matterSelcontainer.startDataTime = this.matterSelcontainer.startDataTime.AddDays(1);
                        }

                        // 平均 列
                        DataGridTextColumn templateColumnAVG = new DataGridTextColumn();
                        templateColumnAVG.Header = "平均";
                        colNum++;//平均 [日期的最后一个下标加1]
                        templateColumnAVG.Binding = new Binding("[" + colNum + "]");

                        //绑定单元格样式
                        templateColumnAVG.CellStyle = App.Current.Resources["DataGrid_Cell_Right"] as Style;
                        //将列加到DataGrid中
                        dgFormProject.Columns.Add(templateColumnAVG);

                        //冻结两列
                        this.dgFormProject.FrozenColumnCount = 2;

                        #endregion 动态生成 DataGarid

                        // dataListToCSV记录 导出数据的内容
                        this.dataListToCSV = null;
                        this.dataListToCSV = getListSource;

                        //查询按钮可用
                        this.matterSelcontainer.btnSelList.IsEnabled = true;

                        Dispatcher.BeginInvoke(() => DataContext = false);
                        this.nuPageSize.IsEnabled = true; //分页数量 09/28/2010 Add

                        this.wcfLogClient.InfoAsync(((App)Application.Current).LogStr + 
                                                        "在 "+this.ctrlName +" 中查询记录" +
                                                        matterSelcontainer.WhereIntorLogs);
                     }
                    else
                    {
                        this.dgFormProject.ItemsSource = null;
                        this.dpDataPage.DataContext = null;

                        this.dataListToCSV = null;

                        this.wcfLogClient.InfoAsync(((App)Application.Current).LogStr + 
                                                    "在 "+this.ctrlName +" 中没有查询到记录" +
                                                    matterSelcontainer.WhereIntorLogs);

                        throw new Exception(this.ctrlName +" 查询中没有可显示的OP数据");
                    }
                }
                else
                {
                    throw new Exception("WCFOPPEntryClient_SelectFormProjectQueryInforCompleted 服务返回值有错" + e.Error.Message.ToString());
                }
            }
            catch(Exception exce) 
            {
                Dispatcher.BeginInvoke(() => DataContext = false);
                this.nuPageSize.IsEnabled = true; //分页数量 09/28/2010 Add
                //查询按钮可用
                this.matterSelcontainer.btnSelList.IsEnabled = true;

                string exceptionStr = FunctionClass.GetMessageInformation(exce);

                this.wcfLogClient.ErrorAsync(((App)Application.Current).LogStr +
                                                    ctrlName +"FormProjectQueryCtrl"+
                                                    exceptionStr +
                                                    matterSelcontainer.WhereIntorLogs);

                FunctionClass.ShowMessageBox(
                   this.errorMessbox,
                   1,
                   "提示",
                   exceptionStr,
                   Colors.Gray,
                   true,
                   Visibility.Visible,
                   Visibility.Collapsed);
                return;
            }
        }

        #endregion 查询符合条件的OP信息(查询按钮)

        #region BusyBar
        /// <summary>
        /// 让BusyBar开始
        /// SetBusyBar
        /// </summary>
        /// <param name="busySeconds">busy秒数 busysecond</param>
        public void SetBusyBar(int busySeconds)
        {
            int delayMilliseconds = 2;
            biBusyBar.DisplayAfter = TimeSpan.FromMilliseconds(delayMilliseconds);

            DataContext = true;
            this.nuPageSize.IsEnabled = false; //分页数量 09/28/2010 Add
            ThreadPool.QueueUserWorkItem((state) =>
            {
                Thread.Sleep(busySeconds * 1000);
            });
        }
        #endregion BusyBar

        #region 数据导出

        /// <summary>
        /// 导出开始
        /// ExportCommand_ExecBegin
        /// </summary>
        /// <param name="sender">sender of object</param>
        /// <param name="e">e type of EventArgs</param>
        private void ExportCommand_ExecBegin(object sender, EventArgs e)
        {
            this.ExportDate();
        }

        /// <summary>
        /// 导出 按钮  
        /// ExportDate
        /// </summary>        
        private void ExportDate()
        {
            try
            {
                //设置 查询界面 的 数据导出 可用
                this.matterSelcontainer.btnExport.IsEnabled = true;

                if (this.dgFormProject.ItemsSource == null)
                {
                    throw new Exception("请查询后再将数据导出。");
                }
                else
                {
                    this.ExportDataToFile(this.dgFormProject);
                }
            }
            catch (Exception ex)
            {
                this.wcfLogClient.ErrorAsync(((App)Application.Current).LogStr + 
                                                " ExportDate("+this.ctrlName +") " + 
                                                ex.Message.ToString() +
                                                matterSelcontainer.WhereIntorLogs);
                FunctionClass.ShowMessageBox(
                    this.errorMessbox,
                    1,
                    "提示",
                   ex.Message.ToString(),
                   Colors.Gray,
                   true,
                   Visibility.Visible,
                   Visibility.Collapsed);
                return;
            }
        }

        /// <summary>
        /// 数据导出
        /// ExportDataToFile
        /// </summary>
        /// <param name="grid">带有显示格式的 grid</param>
        /// <value>10/14/2010 修改 导出功能异常</value>
        private void ExportDataToFile(DataGrid grid)
        {
            try
            {
                SaveFileDialog sfd = new SaveFileDialog();
                sfd.DefaultExt = "csv";
                sfd.Filter = "CSV Files (*.csv)|*.csv|All files (*.*)|*.*";

                sfd.FilterIndex = 1;
                bool? ret = sfd.ShowDialog();
                if (ret == true)
                {
                    string data = DataExport.ExportDataGrid(true, grid, null, this.dataListToCSV);

                    using (System.IO.Stream stream = sfd.OpenFile())
                    {
                        using (System.IO.StreamWriter writer = new System.IO.StreamWriter(stream, System.Text.UnicodeEncoding.Unicode))
                        {
                            //由 逗号 换成 ^ ,--07/30/2010--EIDT 修改 千分位分割符用TAB替换问题
                            data = data.Replace("^", "\t");
                            writer.Write(data);
                            writer.Close();
                        }

                        stream.Close();
                    }

                    this.wcfLogClient.InfoAsync(((App)Application.Current).LogStr + 
                                                "在 "+this.ctrlName +" 查询中导出记录" +
                                                matterSelcontainer.WhereIntorLogs);

                    FunctionClass.ShowMessageBox(
                      this.errorMessbox,
                      0,
                     "提示",
                     "数据已导出。",
                     Colors.Gray,
                     true,
                     Visibility.Visible,
                     Visibility.Collapsed);
                    return;
                }
                else
                {
                    return;
                }
            }
            catch (Exception ex)
            {
                this.wcfLogClient.ErrorAsync(((App)Application.Current).LogStr +
                                        " ExportDataToFile("+this.ctrlName +") " +
                                        ex.Message.ToString() +
                                        matterSelcontainer.WhereIntorLogs);

                FunctionClass.ShowMessageBox(
                    this.errorMessbox,
                    1,
                   "提示",
                   ex.Message.ToString(),
                   Colors.Gray,
                   true,
                   Visibility.Visible,
                   Visibility.Collapsed);
                return;
            }
        }

        #endregion 数据导出
    }
}
